本篇同步發布於Blog:[解題] LeetCode - 387 First Unique Character in a String
LeetCode
387 - First Unique Character in a String
https://leetcode.com/problems/first-unique-character-in-a-string/
給一個字串s,求它第一個只出現一次的字元的索引值,假如找不到則回傳-1。題目保證只有小寫英文字元。
比如範例輸入s = "leetcode",l是第1個出現且只出現一次的字元,所以回傳它的索引值0。
建立2維度的陣列(或者List),第1維度是字母a - z的索引值,第2維度是該字元的出現位置。s字串從頭掃描一遍,記錄每個字元的出現位置。最後再從2維陣列找出現位置只有1個且位置是最小的。
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
vector<vector<int>> checkChars(26);
for(int i = 0 ; i < s.length();++i){
checkChars[s[i] - 'a'].push_back(i);
}
bool isUniqueFind = false;
int minIndex = 99999999;
for(int i = 0 ; i < 26;++i){
if(checkChars[i].size() == 1){
isUniqueFind = true;
if(checkChars[i][0] < minIndex){
minIndex = checkChars[i][0];
}
}
}
if(isUniqueFind){
return minIndex;
}
else{
return -1;
}
}
};
int main() {
Solution sol;
cout << sol.firstUniqChar("leetcode") << endl;
cout << sol.firstUniqChar("aabbcc") << endl;
cout << sol.firstUniqChar("abcabcd") << endl;
return 0;
}
using System;
using System.Collections.Generic;
namespace LeetCode387
{
public class Solution {
public int FirstUniqChar(string s) {
List<List<int>> checkChars = new List<List<int>>();
for(int i = 0 ; i < 26;++i){
checkChars.Add(new List<int>());
}
for(int i = 0 ; i < s.Length;++i){
checkChars[s[i] - 'a'].Add(i);
}
bool isUniqueFind = false;
int minIndex = 99999999;
for(int i = 0 ; i < 26;++i){
if(checkChars[i].Count == 1){
isUniqueFind = true;
if(checkChars[i][0] < minIndex){
minIndex = checkChars[i][0];
}
}
}
if(isUniqueFind){
return minIndex;
}
else{
return -1;
}
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
Console.WriteLine(sol.FirstUniqChar("leetcode"));
Console.WriteLine(sol.FirstUniqChar("aabbcc"));
Console.WriteLine(sol.FirstUniqChar("abcabcd"));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/300-399/387.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/300-399/387.cs